<!-- ERC-物资管理-物资入库页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="入库单号">
              <px-input
                v-model="queryParams.inNum"
                placeholder="请输入入库单号"
                autocomplete="off"
                maxlength="50"
                @blur="queryParams.inNum = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="物资名称">
              <px-input
                v-model="queryParams.materialName"
                placeholder="请输入物资名称"
                autocomplete="off"
                maxlength="50"
                @blur="queryParams.materialName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="入库类型">
              <px-select v-model="queryParams.inType" placeholder="请选择" clearable>
                <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.name" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="开始时间" prop="startDate">
              <px-date-picker
                v-model="queryParams.startDate"
                style="width: 100%"
                placeholder="请选择开始时间"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :clearable="false"
                @change="changeStartTime"
              />
            </px-form-item>
          </px-col>
        </px-row>
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="结束时间" prop="endDate">
              <px-date-picker
                v-model="queryParams.endDate"
                style="width: 100%"
                placeholder="请选择结束时间"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="defaultTime"
                @change="changeEndTime"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="操作人" prop="inUserId">
              <px-select-v2 v-model="queryParams.inUserId" filterable clearable :options="contactNameList" placeholder="请选择" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="审核状态" prop="approveStatus">
              <px-select v-model="queryParams.approveStatus" placeholder="请选择" clearable>
                <px-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="采购提醒日期" prop="buyTime">
              <px-select v-model="queryParams.buyTime" placeholder="请选择" clearable>
                <px-option v-for="item in buyTimeList" :key="item.label" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div v-has="'ERC_MATERIAL_IN_ADDMATERIAL'" class="equip-table-btn">
        <px-dropdown trigger="click" @command="addSpareParts">
          <px-button type="primary"
            >新增入库单
            <px-icon style="margin-left: 4px">
              <ArrowDown />
            </px-icon>
          </px-button>
          <template #dropdown>
            <px-dropdown-menu>
              <px-dropdown-item v-for="item in facCodeList" :key="item.id" :command="item.name">{{ item.name }}</px-dropdown-item>
            </px-dropdown-menu>
          </template>
        </px-dropdown>
        <px-button v-has="'ERC_MATERIAL_IN_BATCHDOWNLOAD'" style="margin-right: 8px; margin-left: 8px" type="primary" plain @click="batchDownload"
          >导出</px-button
        >
      </div>
      <px-table :data="tableData" class="equip-table" fit size="small" height="calc(100vh - 353px)" border @selection-change="selectionChange">
        <px-table-column label="序号" min-width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button v-if="item.num" link type="primary" @click="handleView(scope.row)">
              {{ scope.row.inNum }}
            </px-button>
            <px-tooltip v-else-if="item.approveStatus" content="点击查看处理进度" placement="top">
              <px-tag
                effect="plain"
                :style="{
                  cursor: 'pointer',
                  color: `${tagColorList[scope.row.approveStatus]}`,
                  border: `1px solid ${tagBorderColorList[scope.row.approveStatus]}`,
                  backgroundColor: `${tagBgColorList[scope.row.approveStatus]}`
                }"
                @click="handleProcess(scope.row)"
              >
                {{ scope.row.approveStatusName }}
              </px-tag>
            </px-tooltip>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            <px-tooltip
              v-if="
                item.approveStatus &&
                (scope.row.purchaseNum == '' || scope.row.purchaseNum == null) &&
                scope.row.inUserId == userId &&
                scope.row.approveStatus === 'pass' &&
                scope.row.inType === 'NPPA'
              "
              content="点击补充采购信息"
            >
              <span style="cursor: pointer" @click="handlePurchaseNum(scope.row)">
                <px-icon color="#ef4444" :size="20" style="margin-left: 4px; vertical-align: middle">
                  <WarnTriangleFilled />
                </px-icon>
              </span>
            </px-tooltip>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" :width="dynamicWidth" align="center">
          <template #default="scope">
            <div class="optionDiv" style="display: inline-block; width: 100%; white-space: nowrap">
              <px-tooltip content="详情" placement="top">
                <px-button v-has="'ERC_MATERIAL_IN_VIEWMATERIAL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
              <!-- 已驳回状态+是创建人才能编辑 -->
              <px-tooltip
                v-if="(scope.row.approveStatus === 'init' || scope.row.approveStatus === 'reject_modify') && userId === scope.row.inUserId"
                content="编辑"
                placement="top"
              >
                <px-button
                  v-has="'ERC_MATERIAL_IN_EDITMATERIAL'"
                  style="margin-left: 6px"
                  link
                  type="primary"
                  icon="EditPen"
                  @click="handleEdit(scope.row)"
                />
              </px-tooltip>
              <!-- 审核中状态+岗位才能审核--根据所属岗位判断 -->
              <px-tooltip v-if="scope.row.approveStatus === 'approving' && isUserId" placement="top" content="审核">
                <px-button v-has="'ERC_MATERIAL_IN_APPROVALMATERIAL'" style="margin-left: 6px" link type="primary" @click="handleCheck(scope.row)">
                  <component :is="markRaw(stamp)" />
                </px-button>
              </px-tooltip>
              <!-- 审核中状态+岗位才能转审 --根据所属岗位判断 -->
              <!-- <px-tooltip v-if="scope.row.approveStatus === 'approving' && isUserId1" content="转审" placement="top">
                <px-button
                  v-has="'ERC_MATERIAL_IN_TRANSFERMATERIAL'"
                  style="margin-left: 6px"
                  link
                  type="primary"
                  icon="Stamp"
                  @click="handleToCheck(scope.row)"
                />
              </px-tooltip> -->
              <!-- 判断草稿状态的物资工单删除按钮 -->
              <px-tooltip v-if="userId === scope.row.inUserId && scope.row.approveStatus === 'init'" content="删除" placement="top">
                <px-button
                  v-has="'ERC_MATERIAL_IN_DELETE'"
                  style="margin-left: 6px"
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                />
              </px-tooltip>
              <!-- 判断审核不通过状态的物资工单删除按钮 -->
              <px-tooltip v-if="scope.row.approveStatus === 'reject'" content="删除" placement="top">
                <px-button
                  v-has="'ERC_MATERIAL_IN_REJECTDELETE'"
                  style="margin-left: 6px"
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                />
              </px-tooltip>
            </div>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddMaterialDetail
      :addType="addType"
      :rowData="rowData"
      :isMain="isMain"
      :isView="isView"
      :drawerType="drawerType"
      :username="username"
      :sparePartsId="sparePartsId"
      :userId="userId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewMaterialDetail
      :num="numPlus"
      :isMain="isMain"
      :isView="isView"
      :sparePartsId="sparePartsId"
      :username="username"
      :userId="userId"
      :rowData="rowData"
      @backMainPage="backMainPage"
      @queryTable="queryTable"
    />
    <!-- 审核弹窗 -->
    <CheckDialog
      :username="username"
      :dialogVisible="checkVisible"
      :busId="sparePartsId"
      :approverId="userId"
      :approverName="approverName"
      @closeDialog="
        checkVisible = false;
        queryTable();
      "
    />
    <!-- 转审弹窗 -->
    <ToCheckDialog
      :username="username"
      :dialogVisible="toCheckVisible"
      :busId="sparePartsId"
      :approverId="userId"
      :approverName="approverName"
      type="wareHousing"
      @closeDialog="
        toCheckVisible = false;
        queryTable();
      "
    />
    <!-- 审核进度弹窗 -->
    <ProcessDialog :dialogVisible="processVisible" :sparePartsId="sparePartsId" @closeDialog="processVisible = false" />
    <!-- 采购信息弹窗 -->
    <PurchaseNumDialog
      :dialogVisible="dialogVisible"
      :sparePartsId="sparePartsId"
      @queryTable="queryTable"
      @closeDialog="
        dialogVisible = false;
        queryTable();
      "
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_MATERIAL_IN"
});
import { queryDictData } from "@/api/erc/common";
import { materialInDelete, queryMaterialList, userQueryByPosition } from "@/api/erc/material";
import { useNav } from "@/layout/hooks/useNav";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { markRaw, getCurrentInstance, onMounted, reactive, toRefs, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import AddMaterialDetail from "./components/AddMaterialDetail.vue";
import CheckDialog from "./components/CheckDialog.vue";
import ProcessDialog from "./components/ProcessDialog.vue";
import PurchaseNumDialog from "./components/PurchaseNumDialog.vue";
import ToCheckDialog from "./components/ToCheckDialog.vue";
import ViewMaterialDetail from "./components/ViewMaterialDetail.vue";
import stamp from "@/assets/svg/operation/stamp.svg?component";
const { proxy }: any = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const { username } = useNav();
//设置结束时间默认选择23.59.59
const timeStringToDate = timeStr => {
  const [hours, minutes, seconds] = timeStr.split(":").map(Number);
  const date = new Date();
  date.setHours(hours, minutes, seconds);
  return date;
};
const defaultTime = timeStringToDate("23:59:59"); // 默认时间设置
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  facCodeList: [],
  contactNameList: [],
  statusList: [],
  buyTimeList: [
    {
      label: "2个月需要采购",
      value: 2
    },
    {
      label: "半年内需要采购",
      value: 6
    }
  ],
  addType: "",
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    endDate: ""
  },
  tableColumns: [
    { prop: "inNum", label: "入库单号", minWidth: "180", showOverflowTooltip: true, fixed: "left", num: true },
    { prop: "materialNames", label: "物资名称", minWidth: "120", showOverflowTooltip: true },
    { prop: "inType", label: "入库类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "actTime", label: "申请时间", minWidth: "150", showOverflowTooltip: true },
    { prop: "inDate", label: "入库时间", minWidth: "150", showOverflowTooltip: true },
    { prop: "inUserName", label: "操作人", minWidth: "180", showOverflowTooltip: true },
    { prop: "approveStatus", label: "审核状态", minWidth: "120", showOverflowTooltip: true, approveStatus: true }
  ],
  tableData: [],
  total: 0,
  userId: "",
  drawerType: "add",
  sparePartsId: "",
  approverId: "",
  approverName: "",
  toCheckVisible: false,
  checkVisible: false,
  processVisible: false,
  dialogVisible: false,
  rowData: {},
  isUserId: false, //判断审批权限
  isUserId1: false, //判断转审权限
  numPlus: "",
  selectIds: [],
  dynamicWidth: 0
});
const {
  isMain,
  isView,
  facCodeList,
  contactNameList,
  statusList,
  buyTimeList,
  addType,
  queryParams,
  tableColumns,
  tableData,
  total,
  userId,
  drawerType,
  sparePartsId,
  approverId,
  approverName,
  toCheckVisible,
  checkVisible,
  processVisible,
  dialogVisible,
  rowData,
  isUserId,
  isUserId1,
  numPlus,
  selectIds,
  dynamicWidth
} = toRefs(state);

const tagColorList = {
  init: "#909399", // 草稿
  pass: "#10b981", // 已通过
  approving: "#f59e0b", // 审核中
  reject: "#9254DE", // 已驳回
  reject_modify: "#ef4444" // 驳回修改
};

const tagBorderColorList = {
  init: "#e9e9eb", // 草稿
  pass: "#b7ead9", // 已通过
  approving: "#fce2b6", // 审核中
  reject: "#DDC2FF", // 已驳回
  reject_modify: "#fac7c7" // 驳回修改
};

const tagBgColorList = {
  init: "#f4f4f5", // 草稿
  pass: "#e8f8f3", // 已通过
  approving: "#fef5e6", // 审核中
  reject: "#F2E7FF", // 已驳回
  reject_modify: "#feecec" // 驳回修改
};

// 进入页面时触发
onMounted(() => {
  const { num, approveStatus, time, buyTime } = route.query;
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  if (route?.query && route?.query?.id) {
    numPlus.value = route?.query?.id;
    isMain.value = false;
    isView.value = true;
  } else if (num) {
    numPlus.value = num;
    isMain.value = false;
    isView.value = true;
    querySelectList();
    queryStatustList();
    queryTable();
    queryRecipientIdSelect();
    queryByPosition();
    // queryByPosition1();
  } else {
    if (approveStatus && buyTime) {
      queryParams.value.approveStatus = approveStatus;
      queryParams.value.buyTime = buyTime;
    }
    if (approveStatus) {
      queryParams.value.approveStatus = approveStatus;
    }
    if (approveStatus && time) {
      queryParams.value.approveStatus = approveStatus;
      queryParams.value.startDate = time[0];
      queryParams.value.endDate = time[1];
    }
    isMain.value = true;
    isView.value = true;
    querySelectList();
    queryStatustList();
    queryTable();
    queryRecipientIdSelect();
    queryByPosition();
    // queryByPosition1();
  }
});
// 右侧操作栏宽度自适应
const getOperatorWidth = () => {
  // 默认宽度
  let width = 50;
  // 按钮数量
  let buttonCount = 1;
  const operatorColumn: any = document.getElementsByClassName("optionDiv");
  const array: any = Array.from(operatorColumn);
  // 如果节点数量大于0-循环这个节点，
  if (array.length > 0) {
    array.forEach(item => {
      // 计算 <px-button> 标签的数量
      const buttons = item.getElementsByClassName("px-button");
      if (buttonCount < buttons.length) {
        buttonCount = buttons.length;
      }
    });
    // 如果按钮数量大于1，宽度要加上边距*（按钮数量-1）
    if (buttonCount > 1) {
      width = width + width * (buttonCount - 1);
    }
  }
  return width;
};

//根据岗位ID获取用户信息接口
const queryByPosition = async () => {
  // 消防系统物资出入库审批专员岗位ID
  const data = await userQueryByPosition([59]);
  const arrNew = data.map(item => {
    return item.userId;
  });
  if (arrNew.includes(userId.value)) {
    isUserId.value = true;
  } else {
    isUserId.value = false;
  }
};
// const queryByPosition1 = async () => {
//   // 消防系统物资出入库转审专员岗位ID
//   const data1 = await userQueryByPosition([60]);
//   const arrNew1 = data1.map(item => {
//     return item.userId;
//   });
//   if (arrNew1.includes(userId.value)) {
//     return (isUserId1.value = true);
//   } else {
//     return (isUserId1.value = false);
//   }
// };
// 开始时间;
const changeStartTime = () => {
  if (queryParams.value.startDate && queryParams.value.endDate) {
    if (queryParams.value.startDate > queryParams.value.endDate) {
      queryParams.value.endDate = queryParams.value.startDate;
    }
  }
};
// 结束时间
const changeEndTime = () => {
  if (queryParams.value.startDate && queryParams.value.endDate) {
    if (queryParams.value.startDate > queryParams.value.endDate) {
      queryParams.value.startDate = queryParams.value.endDate;
    }
  }
};
// 获取物资类型下拉框
const querySelectList = async () => {
  facCodeList.value = await queryDictData({ typeCode: "ERC_MATERIAL_IN_TYPE" });
};
//审核状态列表statusList
const queryStatustList = async () => {
  statusList.value = await queryDictData({ typeCode: "MATERIAL_APPROVE_STATUS" });
};
//联系人下拉,获取contactName
const queryRecipientIdSelect = async () => {
  contactNameList.value = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
};
// 查询备件列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value.approveStatus === "") {
    params.approveStatus = null;
  }
  const data: any = await queryMaterialList(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
  setTimeout(() => {
    dynamicWidth.value = getOperatorWidth();
  }, 200);
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 新增物资入库
const addSpareParts = command => {
  drawerType.value = "add";
  addType.value = command;
  isMain.value = false;
  isView.value = false;
};
// 表格多选框选中-批量导出、批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.inNum) {
      selectIds.value.push(item.inNum);
    }
  });
};
// 入库批量导出按钮
const batchDownload = async () => {
  const params = queryParams.value;
  proxy.download("post", "/erc/api/v1/material/in/exportData", params, "物资入库信息.xlsx");
};
// 查看审核进度弹窗
const handleProcess = (row: any) => {
  processVisible.value = true;
  sparePartsId.value = row.inNum;
  approverId.value = row.approverId;
};
//补充采购信息
const handlePurchaseNum = (row: any) => {
  dialogVisible.value = true;
  sparePartsId.value = row.inNum;
};
// 查看物资详情
const handleView = (row: any) => {
  numPlus.value = row.inNum;
  rowData.value = row;
  drawerType.value = "view";
  sparePartsId.value = row.inNum;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
  isMain.value = false;
  isView.value = true;
};
// 编辑物资入库
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  sparePartsId.value = row.inNum;
  approverId.value = row.approverId;
  approverName.value = row.approverName;
  rowData.value = row;
  isMain.value = false;
  isView.value = false;
};
// 审核物资入库
const handleCheck = (row: any) => {
  checkVisible.value = true;
  sparePartsId.value = row.inNum;
};
// 转审物资入库
const handleToCheck = (row: any) => {
  toCheckVisible.value = true;
  sparePartsId.value = row.inNum;
  approverId.value = row.inUserId;
  approverName.value = row.inUserName;
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
// 删除物资入库
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前物资入库单号“${row.inNum}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const id = [];
      id.push(row.id);
      await materialInDelete({
        idList: id
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");
</style>
